package com.indicator.server.controller.indicatorreleation;

import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class IndicatorRelation {

    private boolean isNull(IndicatorNode indicatorNode) {
        if (null == indicatorNode || StringUtils.isEmpty(indicatorNode.getShape())) {
            return false;
        }
        if (indicatorNode.getShape().equals("edge")) {
            if (null == indicatorNode.getSource() && null == indicatorNode.getTarget()) {
                //报错
                return false;
            }
        } else {
            if (null == indicatorNode.getData()) {
                return false;
            }
        }
        return true;
    }

    @Data
    public static class Relation{
        private String left;
        private String right;
    }


    public void relation(List<IndicatorNode> indicatorNodes) {
        Map<String, Relation> map = new HashMap<>();
        Map<String, IndicatorNode> nodeMap = new HashMap<>();
        for (IndicatorNode n : indicatorNodes) {
            if (isNull(n)) {
                continue;
            }
            if (!n.getShape().equals("edge")) {
                String target = Optional
                        .ofNullable(n.getTarget())
                        .orElse(new IndicatorNodeDataTarget()).getCell();
                String source = Optional
                        .ofNullable(n.getSource())
                        .orElse(new IndicatorNodeEdgeSource()).getCell();
                map.computeIfAbsent(source,k->{
                    Relation relation = new Relation();
                    if(StringUtils.isEmpty(relation.getLeft())){
                        relation.setLeft(target);
                    }else {
                        relation.setRight(target);
                    }
                    return relation;
                });
                continue;
            }
            nodeMap.put(n.getKey(), n);
        }
    }
}
